package app.action;

import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.LinkedList;
import java.util.Scanner;

import javax.swing.JButton;
import javax.swing.JFileChooser;

import app.ui.AbsCommonPanel;
import app.ui.WorkPanel;

public class WorkPanelAction extends AbsCommonPanelAction {

	protected WorkPanel mPanel;
	protected File dir;
	protected File ltn;
	protected JFileChooser fileChooser;

	public WorkPanelAction(AbsCommonPanel absCommonPanel) {
		super(absCommonPanel);

		fileChooser = new JFileChooser(mPanel.getmFrame().getAppUtilities().getLastLocation());
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		Object obj = e.getSource();

		if(obj instanceof JButton) {
			JButton jButton = (JButton) obj;
			switch (jButton.getText()) {
				case "Directory":
					fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
					if(fileChooser.showOpenDialog(mPanel) == JFileChooser.APPROVE_OPTION) {
						dir = fileChooser.getSelectedFile();
						if(dir != null) {
							mPanel.getmFrame().getAppUtilities().getProp().setProperty(AbsAppUtilities.LAST_LOCATION, dir.getParent());
							mPanel.setTextFldDir(dir.getPath());
						}
					}
					break;
				case "List Name":
					fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
					if(fileChooser.showOpenDialog(mPanel) == JFileChooser.APPROVE_OPTION) {
						ltn = fileChooser.getSelectedFile();
						if(ltn != null) {
							mPanel.getmFrame().getAppUtilities().getProp().setProperty(AbsAppUtilities.LAST_LOCATION, ltn.getParent());
							mPanel.setTextFldLtn(ltn.getAbsolutePath());
						}
					}
					break;
				case "Compare":
					if(ltn != null && dir != null) {
						doComparison();
					}
					else {
						mPanel.setTextlblSta("State: Directory or NameList was not set!");
					}
					break;

				default:
					break;
			}
		}
	}

	private void doComparison() {
		FileUtilities fileUtilities = mPanel.getmFrame().getAppUtilities().getFileUtilities();
		LinkedList<String> listOfNames = new LinkedList<>();
		fileUtilities.listAllFiles(dir, listOfNames);

		StringBuilder sBuilder = new StringBuilder();
		for(String str : listOfNames) {
			sBuilder.append(str);
		}

		Scanner scanner;
		String strFileNames = sBuilder.toString();
		String tmp;
		LinkedList<String> missingFiles = new LinkedList<>();
		int cout = 0;
		try {
			scanner = new Scanner(ltn);
			while (scanner.hasNextLine()) {
				tmp = scanner.nextLine();
				if(!strFileNames.contains(fileUtilities.removeExtension(tmp))) {
					missingFiles.add(tmp);
				}
				else {
					cout++;
				}
			}

			mPanel.diplayData(cout, missingFiles);
		}catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void doCatenation() {
		mPanel = (WorkPanel) absCommonPanel;
	}

}
